package file.util;

import file.Constant;
import file.config.FsConfig;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * 非对称加密
 * @author hh
 * @since 2024/12/7
 */
public class SHA256Util {

    private static final String salt = "!23d34fd%#";

    private SHA256Util() {}

    public static String encrypt(String str) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        // 加盐
        messageDigest.update(salt.getBytes(StandardCharsets.UTF_8));
        return byte2Hex(messageDigest.digest(str.getBytes(StandardCharsets.UTF_8)));
    }

    private static String byte2Hex(byte[] digestBytes) {
        StringBuilder builder = new StringBuilder();
        for (byte digestByte : digestBytes) {
            String hex = Integer.toHexString(digestByte & 0xff);
            if (hex.length() == 1) {
                builder.append("0");
            }
            builder.append(hex);
        }
        return builder.toString();
    }

    public static boolean validatePwd(String pwd) throws Exception {
        String readPwd = FsConfig.get(Constant.PWD);
        String encrypt = SHA256Util.encrypt(pwd);
        return Objects.equals(readPwd, encrypt);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String encrypt = encrypt("666");
        System.out.println(encrypt);
    }

}
